<script setup lang="ts">
import type { DeptModelArray, EmpExprModel, EmpModel, EmpModelArray, PaginationParam, SearchEmpModel } from '@/api/model/model'
import {ref, watch,onMounted} from 'vue'
import {queryPageApi,addApi, queryInfoApi, updateApi, deleteApi} from '@/api/emp'
import { queryAllApi } from '@/api/dept'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules, type UploadProps } from 'element-plus'

// 搜索栏变量
const searchEmp = ref<SearchEmpModel>({
  name: '',
  gender: '',
  begin: '',
  end: '',
  date: []
})
// watch 侦听
// 简单对象 
// const myname = ref<string>('')
// watch(myname,(newVal,oldVal)=>{
//   console.log(`name 的值 ${newVal}---------------------${oldVal}`);
// })

// 侦听 复杂对象的单个属性
/* watch(()=>searchEmp.value.name,(newVal,oldVal)=>{
  console.log(`name 的值 ${newVal}---------------------${oldVal}`);
}) */
// 侦听 复杂对象的全部属性 深度侦听
/* watch(searchEmp,(newVal,oldVal)=>{
  console.log(`name 的值 ${newVal.name}---------------------${oldVal.name}`);
},{deep:true}) */

watch(()=>searchEmp.value.date,(newVal,oldVal)=>{
  if(newVal){
    searchEmp.value.begin = newVal[0]
    searchEmp.value.end = newVal[1]
  }else{
     searchEmp.value.begin =''
    searchEmp.value.end = ''
  }

})

// 列表数据展示
const tableData = ref<EmpModelArray>([]) 

//分页组件
const pagination = ref<PaginationParam>({
  currentPage: 1,
  pageSize: 5,
  total: 0
})
//每页显示条数发生变化
const handleSizeChange=(pageSize:number)=>{
  pagination.value.pageSize = pageSize
  queryPage();
}
// 页码发生变化 触发函数
const handleCurrentChange=(page:number)=>{
  pagination.value.currentPage=page
  queryPage();
}
// 分页查询
const queryPage=async()=>{
  const result = await queryPageApi(
    searchEmp.value.begin,
     searchEmp.value.end,
      searchEmp.value.gender,
       searchEmp.value.name,
       pagination.value.currentPage,
       pagination.value.pageSize
  )

  if(result.code){
    tableData.value = result.data.rows
    pagination.value.total=result.data.total
  }


}

// 钩子函数
onMounted(()=>{
  queryPage();
  queryAllDepts();
})

//  ---------------------------多选功能

let selectIds=ref<number[]>([])

const handleSelectionChange=(selections: any[])=>{
selectIds.value=selections.map(item => item.id)
 }


//  --------------------------清空重置条件
const reset=()=>{
  searchEmp.value={
  name: '',
  gender: '',
  begin: '',
  end: '',
  date: []
}
queryPage()
}

// --------------------------------员工的新增操作-----------
let emp =ref<EmpModel>({
  username: '',
  password: '',
  name: '',
  gender: '',
  phone: '',
  job: '',
  salary: '',
  image: '',
  entryDate: '',
  deptId: '',
  exprList: []
})

const add=()=>{
  dialogFormVisible.value=true
  formTitle.value='新增员工'
}

const dialogFormVisible= ref<boolean>(false)
const formTitle=ref<string>('') // 表单的标题
const labelWidth=ref<number>(80)

//性别列表数据
const genders = ref([{ name: '男', value: 1 }, { name: '女', value: 2 }])
//职位列表数据
const jobs = ref([{ name: '班主任', value: 1 },{ name: '讲师', value: 2 },{ name: '学工主管', value: 3 },{ name: '教研主管', value: 4 },{ name: '咨询师', value: 5 },{ name: '其他', value: 6 }])

// 部门列表数据
const depts = ref<DeptModelArray>([])

const queryAllDepts = async()=>{
  const result =await queryAllApi()
  if(result.code){
   depts.value=result.data
  }

}
//  头像上传 
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  emp.value.image=response.data
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('Avatar picture must be JPG  png format!')
    return false
  }
  return true
}
//  添加工作经历

const addWorkItem=()=>{
  // 给员工的工作经历 添加一条数据
  emp.value.exprList.push({
    exprDate: [],
    begin: '',
    end: '',
    company: '',
    job: ''
  })
}

const delWorkItem=(expr:EmpExprModel)=>{
if(emp.value.exprList){
  // 获取传入参数的对应索引
 const index= emp.value.exprList.indexOf(expr)
 if(index !=-1){
  emp.value.exprList.splice(index,1)
 }
}


}

// 通过watch侦听 实现 员工工作经历 开始和结束时间的填充
watch(emp,(newVal,oldVal)=>{
  if(emp.value.exprList){
    emp.value.exprList.forEach(expr =>{
      if(expr.exprDate && expr.exprDate.length >0){
        expr.begin=expr.exprDate[0]
        expr.end=expr.exprDate[1]
      }
    })
  }
},{deep:true})

// 新增员工

const save=async(from:FormInstance | undefined)=>{
  if(!from) return
  from.validate(async(valid)=>{
     let result;
    if(valid){
      // 如果有ID 做的 更新操作
      if(emp.value.id){
         result=await updateApi(emp.value)
      }else{
        // 没有ID,做的是新增
        result =await addApi(emp.value)
      }
      console.log(result.code);
      
  if(result.code){
    ElMessage.success('操作成功')
    dialogFormVisible.value=false
    queryPage()
  }else{
    ElMessage.error(result.msg)
  }
    }
  })
}

// 表单校验
//表单校验规则
const empFormRef = ref<FormInstance>()
const rules = ref<FormRules<EmpModel>>({
  username: [
    { required: true, message: '用户名为必填项', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度为2-20个字', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '姓名为必填项', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度为2-10个字', trigger: 'blur' }
  ],
  gender: [{ required: true, message: '性别为必填项', trigger: 'change' }],
  phone: [
    { required: true, message: '手机号为必填项', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/g, message: '请输入合法的手机号', trigger: 'blur' }
  ],
  salary: [
    { pattern: /^[1-9]\d*$/g, message: '请输入合法的数字', trigger: 'blur' }
  ]
})
// 表单重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
//------------------------------------ 员工修改
// 编辑对话框 弹出
const updateEmp=async(id:number)=>{
  dialogFormVisible.value=true
  formTitle.value='修改员工'

  let result =await queryInfoApi(id)

   if(result.code){
    emp.value=result.data
    // 处理工作经历中的时间范围
    let exprList= emp.value.exprList;
    if(exprList &&exprList.length >0){
      exprList.forEach(expr => {
        expr.exprDate=[expr.begin,expr.end]
      })
    }
   }
}
// 根据ID进行删除  单条数据
const delById=(id:number)=>{
   ElMessageBox.confirm(
    '您确认要删除此数据吗?',
    '删除员工',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async() => {
    // 执行删除操作
    const result =await deleteApi(id+'')
    if(result.code){
      ElMessage.success('删除成功')
      queryPage()
    }else{
      ElMessage.error(result.msg)
    }
    })
    .catch(() => {
      ElMessage.info('取消删除')
    })

}

const delByIds=()=>{
  ElMessageBox.confirm(
    '您确认要删除此数据吗?',
    '删除员工',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async() => {
    // 执行删除操作
    //selectIds ----->[1,2,3]------->1,2,3
    const result =await deleteApi(selectIds.value.join(','))
    if(result.code){
      ElMessage.success('删除成功')
      queryPage()
    }else{
      ElMessage.error(result.msg)
    }
    })
    .catch(() => {
      ElMessage.info('取消删除')
    })



}

</script>

<template>
   <!-- 搜索栏 -->
  <el-form :inline="true" :model="searchEmp" class="demo-form-inline">
    <el-form-item label="姓名">
      <el-input v-model="searchEmp.name" placeholder="请输入姓名"/>
    </el-form-item>

    <el-form-item label="性别">
      <el-select v-model="searchEmp.gender" placeholder="请选择">
        <el-option label="男" value="1" />
        <el-option label="女" value="2" />
      </el-select>
    </el-form-item>

    <el-form-item label="入职时间">
      <el-date-picker
        v-model="searchEmp.date"
        type="daterange"
        range-separator="到"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        value-format="YYYY-MM-DD"
      />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="queryPage">查询</el-button>
      <el-button @click="reset">清空</el-button>
    </el-form-item>
  </el-form>

  <!-- 功能按钮 -->
  <el-button type="success" @click="add();resetForm(empFormRef)">+ 新增员工</el-button>
  <el-button type="danger" @click="delByIds">- 批量删除</el-button>
  <br><br>

  <!-- {{searchEmp}} -->
  <!-- <input v-model="myname"> -->
    <!-- 列表展示 -->
  <el-table :data="tableData" border style="width: 100%" fit 
   @selection-change="handleSelectionChange"
  >
     <el-table-column type="selection" width="50"></el-table-column>
    <el-table-column prop="name" label="姓名" align="center" width="130px" />
    <el-table-column prop="gender" label="性别" align="center" width="100px">
       <template #default="scope">
        {{scope.row.gender == 1 ? '男' : '女'}}
       </template>
    </el-table-column>
    <el-table-column prop="image" label="头像" align="center">
      <template #default="scope">
        <img :src="scope.row.image" width="50px">
      </template>
    </el-table-column>
    <el-table-column prop="deptName" label="所属部门" align="center" />
    <el-table-column prop="job" label="职位" align="center" width="100px">
       <template #default="scope">
        <span v-if="scope.row.job == 1">班主任</span>
        <span v-else-if="scope.row.job == 2">讲师</span>
        <span v-else-if="scope.row.job == 3">学工主管</span>
        <span v-else-if="scope.row.job == 4">教研主管</span>
        <span v-else>其他</span>
       </template>
    </el-table-column>
    <el-table-column prop="entryDate" label="入职时间" align="center" width="130px" />
    <el-table-column prop="updateTime" label="最后修改时间" align="center" />
    <el-table-column label="操作" align="center">
      <template #default="scope">
        <el-button type="primary" size="small" @click="updateEmp(scope.row.id);resetForm(empFormRef)">编辑</el-button>
        <el-button type="danger" size="small" @click="delById(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <br>

  <!-- 分页组件Pagination -->
  <el-pagination
    v-model:current-page="pagination.currentPage"
    v-model:page-size="pagination.pageSize"
    :page-sizes="[5, 10, 20, 50, 100]"
    layout="total, sizes, prev, pager, next, jumper"
    :total="pagination.total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />


<!-- 新增 修改对话框 -->
 <!-- 新增员工 / 修改员工的 DiaLog对话框 -->
  <el-dialog v-model="dialogFormVisible" :title="formTitle">
    <el-form :model="emp" :rules="rules" ref="empFormRef">
      <!-- 第一行 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户名" :label-width="labelWidth" prop="username">
            <el-input v-model="emp.username" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" :label-width="labelWidth" prop="name">
            <el-input v-model="emp.name" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 第二行 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="性别" :label-width="labelWidth" prop="gender">
            <el-select v-model="emp.gender" placeholder="请选择" style="width: 100%;">
              <el-option v-for="gender in genders "  :label="gender.name"  :value="gender.value"  :key="gender.value"></el-option>
              
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" :label-width="labelWidth" prop="phone">
            <el-input v-model="emp.phone" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="薪资" :label-width="labelWidth" prop="salary">
            <el-input v-model="emp.salary" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入职日期" :label-width="labelWidth">
            <el-date-picker v-model="emp.entryDate" type="date" placeholder="请选择入职日期" value-format="YYYY-MM-DD" style="width: 100%;"/>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第四行 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="所属部门" :label-width="labelWidth">
            <el-select v-model="emp.deptId" placeholder="请选择" style="width: 100%;">
              <el-option v-for="dept in depts"  :label="dept.name" :value="dept.id" :key="dept.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="职位" :label-width="labelWidth">
            <el-select v-model="emp.job" placeholder="请选择" style="width: 100%;">
              <el-option v-for="job in jobs"  :label="job.name" :value="job.value" :key="job.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第五行 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="头像"  :label-width="labelWidth">
            <el-upload
    class="avatar-uploader"
    action="/api/upload"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="emp.image" :src="emp.image" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第六行 -->
      <el-row>
        <el-col :span="24">
          <el-form-item label="工作经历" :label-width="labelWidth">
            <el-button type="success" size="small" @click="addWorkItem">+ 添加工作经历</el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第七行 -->
      <el-row :gutter="5" v-for="expr in emp.exprList">
        <el-col :span="10">
          <el-form-item label="时间" size="small" :label-width="labelWidth">
            <el-date-picker type="daterange"  v-model="expr.exprDate" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD"/>
          </el-form-item>
        </el-col>
        
        <el-col :span="6">
          <el-form-item label="公司" size="small">
            <el-input placeholder="公司名称" v-model="expr.company"/>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="职位" size="small">
            <el-input placeholder="职位名称" v-model="expr.job" />
          </el-form-item>
        </el-col>

        <el-col :span="2">
          <el-form-item size="small">
            <el-button type="danger" @click="delWorkItem(expr)">- 删除</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false;resetForm(empFormRef)">取消</el-button>
        <el-button type="primary" @click="save(empFormRef)">确定</el-button>
      </span>
    </template>
    <!-- {{depts}} -->
    {{emp}}
  </el-dialog>



</template>

<style scoped>

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

</style>